package xmlcreator;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

//IMPORTS for XML Schema
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;

public class RegistrationForm extends javax.swing.JFrame
{
    List myData;
    Document dom;
    int registration_id = 1;

    /**
     * This method creates a DOM Tree, prints an XML to a file, and stores XML in the database
     */
    public void runExample()
    {
        System.out.println("Started .. ");
        createDOMTree();
        int XmlCheck = printXMLToFile();

        //If the user input is not valid, do not store the data in database.
        if(XmlCheck == 0)
        {
            jLabel7.setText("There is an error in entering the information! ");
            jLabel8.setText("The UserName must contain only letters! ");
            jLabel9.setText("The Password must be at least 8 characters long: any combination of letters or/and numbers! ");
            jLabel10.setText("The Registration ID number must be a number between 0 and 1000! ");
            jLabel11.setText("The Email must have a valid format! ");
            return;
        }
        else
        {
            jLabel7.setText("Your information has been successfully submitted!");
            jLabel8.setText("An invoice will be sent to you through email!");
            jLabel9.setText("Please make a payment to complete the registration process!");
        }

        storeData();
        System.out.println("The file has been successfully generated!");
    }

    /**
     * STEP 1
     * Add a list of users to the list
     * @return 1 if the user input is valid
     *         0 if the user input is not valid
     */
    private int saveDataToList()
    {
        StringBuilder sb = new StringBuilder();
        sb = new StringBuilder();
        sb.append(jTextField3.getText().toString());
        for(int i = 0; i < sb.length(); i++)
        {
            if(Character.isLetter(sb.charAt(i)))
            {
                jLabel7.setText("Your 'Player Registration ID number' should be a number!");
                return 0;
            }
        }

        if(jTextField1.getText().equals("") || jTextField2.getText().equals("") || jTextField3.getText().equals("") || jTextField4.getText().equals("")){
            jLabel7.setText("Please provide all the information!");
            return 0;
        }

        myData.add(new User(jTextField1.getText().toString(), jTextField2.getText().toString(),
        Integer.parseInt(jTextField3.getText()), jTextField4.getText().toString()));

        return 1;
    }

    // STEP 6
    public void storeData()
    {
        String url = "jdbc:mysql://repos.insttech.washington.edu/";
	String dbName = "lhansel";
	String driver = "com.mysql.jdbc.Driver";
	String userName = "lhansel";
	String password = "GescopBi";
	Statement stmt = null;
	Connection con;

        try
        {
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url+dbName,userName,password);
            String queryString = "INSERT INTO OlympicRegistration (id, xml_file) values " +
                            "(" + registration_id
                             + ",'<Users><User>" +
                                       "<UserName>"+jTextField1.getText()+  "</UserName>" +
                                       "<Password>"+jTextField2.getText()+  "</Password>" +
                                       "<UserID>"  +jTextField3.getText()+  "</UserID>"   +
                                       "<Email>"   +jTextField4.getText()+  "</Email>"    +
                                 "</User></Users>')";
            stmt=con.createStatement();
            int val = stmt.executeUpdate(queryString);
            registration_id++;
        }
	catch(Exception e)
	{
            System.out.println("e : " + e);
	}
    }

    /**
     * STEP 2
     * Using JAXP in implementation independent manner to create a document object
     * so that we create a xml tree in memory
     */
    private void createDocument()
    {
        //get an instance of factory
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
        //get an instance of builder
        DocumentBuilder db = dbf.newDocumentBuilder();
        //create an instance of DOM
        dom = db.newDocument();
        }
        catch(ParserConfigurationException pce)
        {
            System.out.println("Error while trying to instantiate DocumentBuilder " + pce);
            System.exit(1);
        }
    }

    /**
     * STEP 4
     * The function creates the XML structure
     */
    private void createDOMTree()
    {
        //create the root element <Users>
        Element rootEle = dom.createElement("Users");
        dom.appendChild(rootEle);

        //No enhanced for
        Iterator it  = myData.iterator();
        while(it.hasNext())
        {
            User b = (User)it.next();
            //For each User object create <User> element and attach it to root
            Element userEle = createUserElement(b);
            rootEle.appendChild(userEle);
        }
    }

    /**
     * STEP 3
     * Helper method which creates a XML element <User>
     * @param u The user for which we need to create an xml representation
     * @return XML element snippet representing a user
     */
    private Element createUserElement(User u){

        Element UserEle = dom.createElement("User");

        //create username element & username text node and attach it to userElement
        Element usernameEle = dom.createElement("UserName");
        Text usernameText = dom.createTextNode(u.getUsername());
        usernameEle.appendChild(usernameText);
        UserEle.appendChild(usernameEle);

        //create password element & password text node and attach it to userElement
        Element passwordEle = dom.createElement("Password");
        Text passwordText = dom.createTextNode(u.getPassword());
        passwordEle.appendChild(passwordText);
        UserEle.appendChild(passwordEle);

        //create userid element & userid text node and attach it to userElement
        Element useridEle = dom.createElement("UserID");
        Text useridText = dom.createTextNode(String.valueOf(u.getUserid()));
        useridEle.appendChild(useridText);
        UserEle.appendChild(useridEle);

        //create email element & email text node and attach it to userElement
        Element emailEle = dom.createElement("Email");
        Text emailText = dom.createTextNode(u.getEmail());
        emailEle.appendChild(emailText);
        UserEle.appendChild(emailEle);

        return UserEle;
    }

    /**
     * STEP 5
     * This method uses Xerces specific classes
     * that prints the XML document to file.
     */
    private int printXMLToFile()
    {
        int XmlCheck = 1;
        try
        {
            //print
            OutputFormat format = new OutputFormat(dom);
            format.setIndenting(true);

            //to generate output to console use this serializer
            //XMLSerializer serializer = new XMLSerializer(System.out, format);

            //to generate a file output use fileoutputstream instead of system.out
            @SuppressWarnings("serial")
            XMLSerializer serializer = new XMLSerializer(new FileOutputStream(new File("users.xml")), format);
            serializer.serialize(dom);

            try
            {
                // define the type of schema - we use W3C:
                String schemaLang = "http://www.w3.org/2001/XMLSchema";
                // get validation driver:
                SchemaFactory factory = SchemaFactory.newInstance(schemaLang);
                // create schema by reading it from an XSD file:
                Schema schema = factory.newSchema(new StreamSource("users.xsd"));
                Validator validator = schema.newValidator();
                // at last perform validation:
                validator.validate(new StreamSource("users.xml"));
            }
            catch (SAXException ex)
            {
                // If the document is not valid process a validation error...
                System.out.println(ex.toString());
                XmlCheck = 0;
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
                XmlCheck = 0;
            }
            
        }
        catch(IOException ie)
        {
            ie.printStackTrace();
        }

        return XmlCheck;
    }

    /** Creates new form RegistrationForm */
    public RegistrationForm() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Courier New", 1, 24)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 102, 0));
        jLabel1.setText("SpringHills Tennis 2011 Registration Form");

        jLabel2.setFont(new java.awt.Font("Tahoma", 2, 18)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(102, 0, 102));
        jLabel2.setText("Please fill out the required fields below:");

        jLabel3.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N
        jLabel3.setText("Username");

        jLabel4.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N
        jLabel4.setText("Password");

        jTextField2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField2ActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N
        jLabel5.setText("Player Registration ID Number");

        jLabel6.setFont(new java.awt.Font("Calibri", 0, 24)); // NOI18N
        jLabel6.setText("Email");

        jButton1.setText("Submit");
        jButton1.setFont(new java.awt.Font("Tahoma", 0, 20));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setForeground(new java.awt.Color(153, 0, 0));
        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel8.setForeground(new java.awt.Color(153, 0, 0));
        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel9.setForeground(new java.awt.Color(153, 0, 0));
        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel10.setForeground(new java.awt.Color(153, 0, 0));
        jLabel11.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel11.setForeground(new java.awt.Color(153, 0, 0));

        jTextField1.setFont(new java.awt.Font("Tahoma", 4, 20));
        jTextField2.setFont(new java.awt.Font("Tahoma", 4, 20));
        jTextField3.setFont(new java.awt.Font("Tahoma", 4, 20));
        jTextField4.setFont(new java.awt.Font("Tahoma", 4, 20));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 1000, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 1000, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel10, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel11, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE)
                                .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGap(68, 68, 68)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jTextField4)
                                .addComponent(jTextField3)
                                .addComponent(jTextField2)
                                .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)))))
                .addContainerGap(175, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addGap(18, 18, 18)
                .addComponent(jLabel7)
                .addComponent(jLabel8)
                .addComponent(jLabel9)
                .addComponent(jLabel10)
                .addComponent(jLabel11)
                .addContainerGap(60, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        jLabel7.setText("");
        jLabel8.setText("");
        jLabel9.setText("");
        jLabel10.setText("");
        jLabel11.setText("");

        //create a list to hold the data
        myData = new ArrayList();
        //initialize the list
        int feedback = saveDataToList();
        if(feedback == 1)
        {
            //Get a DOM object
            createDocument();
            runExample();
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new RegistrationForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration//GEN-END:variables

}


